<template>
  <div class="app">
    <div class="header">
      <nav class="container">
        <a href="/weather"
          ><i class="iconfont icon-sun">&nbsp; </i>
          <div>新中地天气</div></a
        >
        <div>{{ currentCity }}</div>
        <div>实时天气：{{ currentWeather }} {{ currentTemperature }}℃</div>
        <div>{{ currentWinddirection }}风 {{ currentWindpower }}级</div>
        <div class="xinxi">
          <el-icon class="icon-hover" @click="handleInfo">
            <InfoFilled />
          </el-icon>

          <el-dialog
            v-model="showDialog"
            title="关于本应用"
            width="400px"
            center
          >
            <p><b>关于：</b><div>这个应用可以用来追踪你选择城市的当前天气。</div></p>
            <p><b>如何使用：</b></p>
            <div style="line-height: 1.8">
              <div>1. 点击搜索框输入你希望追踪的城市。</div>
              <div>2. 在搜索结果中选中一个城市，你将获取当地最新的天气。</div>
              <div>3. 点击右侧的 “＋” 号可以将城市添加到首页。</div>
            </div>
            <p>
              <b>移除城市：</b><div>如果不想关注某个城市，可以在首页点击删除按钮。</div>
            </p>
            <template #footer>
              <el-button type="primary" @click="showDialog = false"
                >知道了</el-button
              >
            </template>
          </el-dialog>
        </div>
      </nav>
    </div>
    <div class="body">
      <div class="search">
        <input
          type="text"
          placeholder="请输入城市名称"
          v-model="inputText"
          @input="fetchCityList"
        />
        <ul v-if="cityList.length">
          <li
            v-for="(city, index) in cityList"
            :key="index"
            @click="handleSwitch(city)"
            style="cursor: pointer"
          >
            {{ city }}
          </li>
        </ul>
        <ul v-else-if="inputText.trim()">
          <li>似乎没有找到你查找的城市</li>
        </ul>
      </div>
      <div class="information">
        <ul v-if="cityStore.savedCities.length" class="saved-city-list">
          <li
            v-for="(city, index) in cityStore.savedCities"
            :key="index"
            class="city-item"
          >
            <span class="city-content">{{ city }}</span>
            <span class="city-temperature">{{ cityTemperatures[city] ? cityTemperatures[city] + '℃' : '加载中...' }}</span>
            <div class="city-actions">
              <el-button @click="handleSwitch(city)">查看</el-button>
              <el-button @click="handleDelete(city)">删除</el-button>
            </div>
          </li>
        </ul>
        <ul v-else>
          <li>暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</li>
        </ul>
      </div>
      <div class="weather">
        <div>近期天气</div>
        <div class="renWea">
          <div class="weaData">
            <div class="content">
              <span>今天</span>
              <span>{{ futureData[0]?.date.slice(5) }}</span>
              <span>{{ futureData[0]?.dayweather }}</span>
              <span>风力 {{ futureData[0]?.daypower }}级</span>
            </div>
            <div class="content">
              <span>明天</span>
              <span>{{ futureData[1]?.date.slice(5) }}</span>
              <span>{{ futureData[1]?.dayweather }}</span>
              <span>风力 {{ futureData[1]?.daypower }}级</span>
            </div>
            <div class="content">
              <span>周{{ numberToWeek[futureData[2]?.week] }}</span>
              <span>{{ futureData[2]?.date.slice(5) }}</span>
              <span>{{ futureData[2]?.dayweather }}</span>
              <span>风力 {{ futureData[2]?.daypower }}级</span>
            </div>
            <div class="content">
              <span>周{{ numberToWeek[futureData[3]?.week] }}</span>
              <span>{{ futureData[3]?.date.slice(5) }}</span>
              <span>{{ futureData[3]?.dayweather }}</span>
              <span>风力 {{ futureData[3]?.daypower }}级</span>
            </div>
          </div>
          <div class="chart"><WeatherChart /></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import WeatherChart from '../components/WeatherChart.vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useWeatherStore } from '@/stores/weather'
import { useSearchStore } from '@/stores/search'
import { useCityStore } from '@/stores/city'
import { ElDialog } from 'element-plus'
import { getAdcodeData, getWeatherData } from '@/utils/index'

const cityStore = useCityStore()

const showDialog = ref(false)
function handleInfo() {
  showDialog.value = true
}

// 输入内容
const inputText = ref('')

// 城市列表
const cityList = ref([])
const router = useRouter()
const cityTemperatures = ref({})

const reportWeather = useWeatherStore()
const searchData = useSearchStore()

const currentCity = ref('')

const currentAdcode = ref('')

const currentWeather = ref('')
const currentTemperature = ref('')
const currentWinddirection = ref('')
const currentWindpower = ref('')

const futureData = ref([])

onMounted(async () => {
  // 触发加载数据
  //通过ip查询城市
  await reportWeather.fetchCityData()
  currentCity.value = reportWeather.cityData.city
  //通过城市查询adcode
  await reportWeather.fetchAdcodeData(currentCity.value)
  currentAdcode.value = reportWeather.adcodeData
  //通过adcode查询城市天气
  await reportWeather.fetchWeatherData(currentAdcode.value)
  await reportWeather.fetchFutureWeatherData(currentAdcode.value)

  currentWeather.value = reportWeather.weatherData.weather
  currentTemperature.value = reportWeather.weatherData.temperature
  currentWinddirection.value = reportWeather.weatherData.winddirection
  currentWindpower.value = reportWeather.weatherData.windpower

  futureData.value = reportWeather.futureWeatherData

  cityStore.loadSavedCities()

  cityStore.savedCities.forEach(city => {
    fetchTemperatureForCity(city)
  })
})

//自定义转换
const numberToWeek = {
  1: '一',
  2: '二',
  3: '三',
  4: '四',
  5: '五',
  6: '六',
  7: '日',
}

// 触发搜索
async function fetchCityList() {
  if (inputText.value.trim()) {
    await searchData.fetchCityList(inputText.value.trim())
    cityList.value = searchData.searchData
  } else {
    cityList.value = []
  }
}
//跳转到搜索/查看页面
function handleSwitch(city) {
  router.push(`/weather/search/${encodeURIComponent(city)}`)
  inputText.value = ''
}

async function fetchTemperatureForCity(city) {
  try {
    const adcodeRes = await getAdcodeData(city)
    const adcode = adcodeRes.geocodes?.[0]?.adcode
    const weatherRes = await getWeatherData(adcode)
    const temp = weatherRes.lives?.[0]?.temperature
    cityTemperatures.value[city] = temp
  } catch (err) {
    cityTemperatures.value[city] = '--'
    console.error(`获取 ${city} 的气温失败：`, err)
  }
}

//点击删除
function handleDelete(city) {
  cityStore.removeCity(city)
}
</script>

<style scoped>
@import 'https://at.alicdn.com/t/c/font_4968282_j9nodh8b0fl.css';
.app {
  min-height: 100vh; /* 将元素高度设置为视口高度的 100% */
  background: #00668a;
  margin: 0px;
  border-radius: 10px;
}
a {
  display: flex;
  gap: 0.25rem;
  font-size: 1.5rem;
  color: white;
  text-decoration: none; /* 移除下划线 */
}
i {
  font-size: 1.5rem; /* 直接设置i标签的字体大小 */
  align-items: center;
}

.xinxi {
  margin-left: auto;
  cursor: pointer;
  padding-top: 5px;
}
.icon-hover {
  transition: color 1.5s ease; /* 平滑过渡 */
}
.icon-hover:hover {
  color: rgba(0, 78, 113, 0.3);
}

.header {
  box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1); /* header与body之间的阴影 */
}
.container {
  color: white;
  display: flex;

  gap: 1rem;
  margin: 0 7rem;
  padding: 1.5rem 10rem;
  align-items: center;
}
.body {
  color: white;
  margin: 0 7rem;
  padding: 0 10rem;
  align-items: center;
}
input {
  width: 100%;
  padding: 8px 4px;
  border: none;
  border-bottom: 1px solid white;
  font-size: 100%;
  color: white;
  background: #00668a;
}
.search {
  padding-top: 1rem;
  margin-bottom: 2rem;
}
ul {
  background: #004e71;
  padding: 8px 4px;
}
li {
  padding: 8px 0px;
  list-style-type: none;
}
.saved-city-list {
  list-style: none;
  padding: 0;
}
.city-item {
  position: relative;
  padding: 8px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.city-temperature{
  position: absolute;
  right: 160px;
  display: flex;
  gap: 8px;
}
.city-actions {
  position: absolute;
  right: 16px;
  top: 50%;
  /* transform: translateX(100%) translateY(-50%);
  transition: transform 0.3s ease; */
  display: flex;
  gap: 8px;
  opacity: 0;
}

.city-item:hover .city-actions {
  opacity: 1;
  transform: translateX(0%) translateY(-50%);
}
.city-actions button {

  /* padding: 4px 8px; */
  font-size: 12px;
  cursor: pointer;
}
.information {
  margin-bottom: 2rem;
  text-align: center;
}
.renWea {
  margin-top: 0.5rem;
  border-radius: 5px;
  padding: 0 48px;
  padding-top: 40px;
  background: #004e71;
}
.weaData {
  display: flex;
  gap: 1.5rem;
}

.content {
  flex: 1;
  display: flex;

  flex-direction: column;
  gap: 1rem;
  text-align: center;
}
.chart {
  margin-top: 40px;
  height: 230px;
}
</style>
